using System.Collections.Generic;
using SimpleJSON;
using TMPro;
using UnityEngine.UI;

namespace Gj
{
    public class DropdownHelper : NodeHelper
    {
        public bool online;
        public bool local;
        public bool pro;
        public Dropdown dropdown;
        public TMP_Dropdown dropdownPro;

        [SelectRef(UIKey.DATA_KEY)] public SelectKey select;

        protected override BindDataType bindDataType => BindDataType.Int;

        protected override void Start()
        {
            if (pro)
                dropdownPro.onValueChanged.AddListener(ChangeDropdownValue);
            else
                dropdown.onValueChanged.AddListener(ChangeDropdownValue);
        }

        public override void SetData(JSONObject json)
        {
            if (!select.IsEmpty())
            {
                if (pro)
                {
                    var list = new List<TMP_Dropdown.OptionData>();
                    foreach (JSONString item in select.Get(json).AsArray)
                        list.Add(new TMP_Dropdown.OptionData(GetText(item.Value)));
                    dropdownPro.options = list;
                }
                else
                {
                    var list = new List<Dropdown.OptionData>();
                    foreach (JSONString item in select.Get(json).AsArray)
                        list.Add(new Dropdown.OptionData(GetText(item.Value)));
                    dropdown.options = list;
                }
            }

            base.SetData(json);
        }

        protected override void BindData(int i)
        {
            if (pro)
                dropdownPro.value = i;
            else
                dropdown.value = i;
        }

        public void ChangeDropdownValue(int i)
        {
            Change(i);
        }

        private string GetText(string s)
        {
            // Debug.LogErrorFormat("{0} {1} {2}", gameObject.name, gameObject.transform.parent.name ,s);
            if (online && !StringTools.IsEmpty(s))
            {
                var o = Localization.Instance.GetOnlineValue(s);
                s = o == "" ? s : o;
            }

            return s;
        }
    }
}